<template>
  <div class="my-container-box">
    <van-nav-bar left-text="返回" left-arrow right-text="打卡记录" @click-left="backPrePage" @click-right="onClickRight">
    </van-nav-bar>
    <div id='container'></div>


    <div id="box">
      <div @click="relocation" style="display: flex">
        <img class="my-rl" :src="rel ">
        <!--        <div class="my-rl-font">重新定位</div>-->
      </div>
      <div class="model-point" style="margin-left: 80%;">
        <van-tag @click="modelSwitch" v-show="model" type="warning">外勤模式</van-tag>
        <van-tag @click="modelSwitch" v-show="!model" type="primary">上班模式</van-tag>
      </div>
      <div>
        <!-------------------------------------单元测试------------------------------------->
        <van-tag @click="calculateTwoPlaceDistance" class="distance" style="margin-left: 80%;">二点距离
        </van-tag>
        <!--                <van-tag @click="calculateMorePlaceDistance" class="distance" style="margin-left: 80%;" type="primary">多点距离-->
        <!--                </van-tag>-->
        <!--                <van-tag @click="compareMaxMin" class="distance" style="margin-left: 80%; " plain type="primary">最短距离</van-tag>-->
        <!--                <van-tag @click="computedRangeToMinChock()" class="distance" style="margin-left: 80%; " plain type="primary">-->
        <!--                  打卡范围-->
        <!--                </van-tag>-->
      </div>

      <!--办公地点-->
      <div v-show="!placeFlag">
        <van-button @click="chock" id='signIn' type="info">{{ this.signName }}
          <p class="my-time">{{ dynamicTime }}</p>
        </van-button>
        <br/>
        <div class="my-icon">
          <img class="my-check" :src="check_icon">
          <i class="my-i"> 已进入考勤范围 </i>
        </div>
        <div class="detail-lo" style="display: flex; ">
          <img class="lo_icon" :src="lo_icon">
          <div class="detail-font">{{ addressDetailName }}</div>
        </div>


      </div>

      <!--非办公地点-->
      <div v-show="placeFlag">
        <van-button @click="unchock" id='fieldclock' color="linear-gradient(to right, #CCD1D9, #656D78)">
          {{ outsideName }}
          <p class="my-time">{{ dynamicTime }}</p>
        </van-button>
        <br>
        <div class="no-sign" style="display: flex"><img class="my-no-check" :src="no_check_icon">
          <i class="my-i2"> 不在考勤范围 </i>
          <i @click="relswitch" class="my-i3"> 重新定位 </i>
          <img @click="relswitch" class="my-restart_locate_icon" :src="restart_locate_icon">
        </div>
        <div class="detail-lo-2" style="display: flex; margin-top: 3%;">
          <img class="lo_icon" :src="lo_icon">
          <div class="detail-font">{{ addressDetailName }}</div>
        </div>
      </div>
      <br/>
      <!--
      微信腾讯地图计算两点（或多点）间距离
      https://www.cnblogs.com/hermitks/p/9350477.html
      -->

      <!--      calculateDistance-->
      <!--      <div id='location'>{{ this.scopeIsNo }}</div>-->
      <!--      经度->{{longitude}}-->
      <!--      纬度->{{latitude}}-->
    </div>

  </div>
</template>
<script>
//移动端和vue接入腾讯地图前端定位组件位置不准确以及自己创建地图
//https://blog.csdn.net/wangzongyang1025_/article/details/106766868
import {Toast} from 'vant';
import QQMapWX from '@/assets/js/qqmap-wx-jssdk.js'
// 引用工具类格式化日期
import dateUtils from '../../utils/dateUtils.js';

export default {
  inject: ['reload'],
  name: 'MapPosition',
  data() {
    return {
      dynamicTime: '',//打卡时间定时器 hh-mm-ss
      model: true,//模式切换 标志
      check_icon: require('@/assets/iconfont/check.png'),// 考勤范围内图标
      no_check_icon: require('@/assets/gps/warn.png'),// 不在考勤范围内图标
      // no_check_icon: require('@/assets/iconfont/no.png'),// 不在考勤范围内图标
      restart_locate_icon: require('@/assets/iconfont/restart_location.png'),//重新定位图标
      rel: require('@/assets/gps/r.png'),//重新定位图标
      lo_icon: require('@/assets/gps/myPosition.png'),//重新定位图标
      signInPlace: [],//签到办公地点 设置的签到点 上海
      placeFlag: false,
      scopeIsNo: '系统正在定位中',
      positionInfo: {},
      signName: "上班签到",
      outsideName: "外勤打卡",
      officeSpace: '办公地点',
      noOfficeSpace: '非办公地点',
      setChockDistance: 100,//设置打卡范围
      longitude: 116.567515,//当前位置的经度,
      latitude: 39.780864,//当前位置的纬度
      qqMap: new QQMapWX({
        key: 'LUXBZ-T2FWJ-Z77FH-KNNWX-BAVH6-ATBE2',
        vm: this
      }),
      addressDetailName: '',// 详细地址信息
      listInfo: [// 接口获取-多办公打卡地的数据，真实场景会从数据库中获取
        //  https://apis.map.qq.com/ws/distance/v1/?mode=driving&from=39.780864,116.567515&to=39.781023,116.567112;39.780621,116.567175;39.780364,116.566577;39.781487,116.565913&key=LUXBZ-T2FWJ-Z77FH-KNNWX-BAVH6-ATBE2
        {
          "name": "3号喽",
          "lat": "39.781023",
          "lng": "116.567112"
        },
        {
          "name": "运动场",
          "lat": "39.780621",
          "lng": "116.567175"
        },
        {
          "name": "6号楼",
          "lat": "39.780364",
          "lng": "116.566577"
        },
        {
          "name": "汇龙森三园东区",
          "lat": "39.781487",
          "lng": "116.565913"
        },
      ],
      moreWorkPlace: '',//多办公打卡地
      moreWorkDistanceListTemp: []// 多办公打卡地与当前经纬度的实际距离
    }
  },
  created() {
    // console.log(this.$route.query.id)
    const id = this.$route.query.id;
    if (id == 2) {
      //初始化 打卡时间定时器
      this.getTime()
    }
    this.morePlace()
  },
  mounted() {
    this.getMyLocation();
  },
  methods: {

    // 官网api：https://lbs.qq.com/service/webService/webServiceGuide/webServiceDistance
    // 案例：https://apis.map.qq.com/ws/distance/v1/?mode=driving&from=39.983171,116.308479&to=39.996060,116.353455;39.949227,116.394310&key=LUXBZ-T2FWJ-Z77FH-KNNWX-BAVH6-ATBE2
    morePlace() {
      const that = this;
      const listBox = that.listInfo;

      for (var i = 0; i < listBox.length; i++) {
        if (i + 1 < listBox.length) {
          this.moreWorkPlace += listBox[i].lat + "," + listBox[i].lng + ";"
        } else {
          this.moreWorkPlace += listBox[i].lat + "," + listBox[i].lng
        }
      }
      // console.log("多办公地点->", this.moreWorkPlace)
    },

    /**
     * 获取时间
     */
    getTime() {
      let that = this
      let dynamicTime = that.dynamicTime
      let timer = setInterval(function () {
        let dynamicTime = dateUtils.formatTime(new Date())
        that.dynamicTime = dynamicTime.substr(-8)
        if (dynamicTime == 0) {
          // 页面跳转后，要把定时器清空掉，免得浪费性能
          clearInterval(that.dynamicTime)
        }
      }, 1000)
    },

    // 模式切换
    modelSwitch() {
      this.placeFlag = !this.placeFlag
      this.model = !this.model
    },

    // 重新定位+切换模式
    relswitch() {
      this.getMyLocation();
      this.placeFlag = !this.placeFlag
      this.model = !this.model
    },

    // 重新定位
    relocation() {
      this.getMyLocation();
    },

    //点击打卡记录
    onClickRight() {
      Toast.success("暂未开放,敬请期待！")
    },

    //回到上一页
    backPrePage() {
      this.$router.go(-1);
    },

    //腾讯位置服务 - 前端定位组件
    //https://lbs.qq.com/webApi/component/componentGuide/componentGeolocation
    //定位获得当前位置信息
    getMyLocation() {
      var geolocation = new qq.maps.Geolocation("LUXBZ-T2FWJ-Z77FH-KNNWX-BAVH6-ATBE2", "kk");
      // geolocation.getIpLocation(this.showPosition, this.showErr);
      geolocation.getLocation(this.showPosition, this.showErr);//或者用getLocation精确度比较高
    },

    //定位成功 处理函数
    showPosition(position) {
      // console.log(position);
      this.latitude = position.lat;
      this.longitude = position.lng;

      //获取经纬度初始化地地图
      this.setMap();
      //根据经纬度获取当前位置
      this.reverseGeocoder()
    },

    // 定位失败异常捕获处理
    showErr() {
      // console.log("定位失败");
      this.getMyLocation();//定位失败再请求定位，测试使用
    },

    // 获取经纬度后，进项将经纬度转换位置描述
    reverseGeocoder() {
      let _this = this
      this.qqMap.reverseGeocoder({
        location: {
          latitude: _this.latitude,
          longitude: _this.longitude
        },
        success: (addressRes) => {
          // console.log("解析后的地址", addressRes)
          this.addressDetailName = addressRes.result.formatted_addresses.recommend; // 解析详细地址信息
          // console.log("解析后的详细地址", this.addressDetailName)
        },
        fail: (res) => {
          // console.error("地址解析异常", res)
        }
      })
    },

    //多点与当前经纬度之间的距离（计算当前经纬度和多地打卡地经纬度之间的距离）
    calculateMorePlaceDistance() {
      const that = this;

      //调用距离计算接口
      that.qqMap.calculateDistance({
        from: {
          latitude: that.latitude,
          longitude: that.longitude
        },
        to: that.moreWorkPlace, //strs为字符串，末尾的“；”要去掉
        success: function (res) {
          // console.log("多地求距离->", res)

          const moreWorkDistanceList = [];
          const distanceList = res.result.elements;
          for (var i = 0; i < distanceList.length; i++) {
            const distAddress = distanceList[i].distance;

            // 把计算出来的距离放到数组容器中，等会统一计算
            moreWorkDistanceList.push(distAddress)
            // console.log("多地打卡数组追加元素->", moreWorkDistanceList);
          }
          /**
           * 转换单位不利于计算，统一用m单位，一起计算，求出数组中最小的一个，最后和设定的办公距离（愿），比较大小；
           * 1.如果小于设置距离，属于考勤范围内
           * 2.如果大于设置距离，属于外勤范围
           */
          that.moreWorkDistanceListTemp = moreWorkDistanceList
          // console.log("多地打卡地与当前位置距离数组:" + that.moreWorkDistanceListTemp);
          alert("多地打卡地与当前位置距离容器:" + that.moreWorkDistanceListTemp)
        },
        fail: function (res) {
          // console.log("求距离发生异常->", res);
        },
        complete: function (res) {
          // console.log("求距离执行完成->", res)
        }
      })
    },

    // 数组中获取最大和最小值
    compareMaxMin() {
      const arr = [12, 56, 25, 5, 82, 51, 22, 100, 2];

      arr.sort(function (a, b) {
        return a - b;
      }); // [5,12,22,25,51,56]

      const min = arr[0];  // 5
      alert("最短距离->" + min)
      // const max = arr[arr.length - 1];  // 56
      // alert("最大值->max", max)
    },
    //计算当前位置与多地打卡最短距离之间的数值，来判断是否属于考勤范围内
    computedRangeToMinChock() {
      const that = this;
      /**
       * 1.获取打卡范围
       * 2.计算多地打卡与当前位置的距离，取最短的一个元素
       * 3.将打卡范围与最短的打卡地进行比较
       *   1>最短距离大于设定的打发范围 不在考勤范围内，属于外勤打卡
       *   2>最短距离大、小于或者等于设定的打发范围 在考勤范围内，属于正常打卡
       */
          // 1.获取打卡范围
      const setChockDistance = that.setChockDistance

      // 2.计算多地打卡与当前位置的距离，取最短的一个元素
      // console.log("that.moreWorkDistanceListTemp", that.moreWorkDistanceListTemp)
      const chockDistance = that.moreWorkDistanceListTemp

      chockDistance.sort(function (a, b) {
        return a - b;
      });
      const minDistance = chockDistance[0];  // 5
      // console.log("距离打卡地最短距离->minDistance", minDistance)

      // 3.将打卡范围与最短的打卡地进行比较
      if (parseInt(minDistance) < parseInt(setChockDistance)) {
        //正常打卡
        alert("正常打卡")
      } else if (parseInt(minDistance) == parseInt(setChockDistance)) {
        //正常打卡
        alert("正常打卡")
      } else {
        //外勤打卡
        alert("外勤打卡")
      }
    },

    //计算二点之间的距离
    calculateTwoPlaceDistance() {
      const _this = this;
      //调用距离计算接口
      _this.qqMap.calculateDistance({
        //mode: 'driving',//可选值：'driving'（驾车）、'walking'（步行），不填默认：'walking',可不填
        //from参数不填默认当前地址
        //获取表单提交的经纬度并设置from和to参数（示例为string格式）
        // from: e.detail.value.start || '', //若起点有数据则采用起点坐标，若为空默认当前地址
        // to: e.detail.value.dest, //终点坐标
        mode: "straight",
        from: "39.77466,116.55859", //当前位置的经纬度
        to: "39.775091,116.56107", //办公地点经纬度 "北京市通州区经海三路137号"
        success: (res) => { //成功后的回调
          // debugger
          // console.log(res);
          let hw = res.result.elements[0].distance; //拿到距离(米)
          // console.log("hw", hw);
          if (hw && hw !== -1) {
            if (hw < 1000) {
              hw = hw + "m";
            }
            //转换成公里
            else {
              hw = (hw / 2 / 500).toFixed(2) + "km";
            }
          } else {
            hw = "距离太近或请刷新重试";
          }
          // console.log("当前位置与办公地点距离:" + hw);
          alert("当前位置与办公地点距离:" + hw)
        },
      });
    },
    //位置信息在地图上展示
    setMap() {
      //步骤：定义map变量 调用 qq.maps.Map() 构造函数   获取地图显示容器
      //设置地图中心点
      const center = new qq.maps.LatLng(this.latitude, this.longitude);
      //定义工厂模式函数
      const myOptions = {
        center: center,  // 地图的中心地理坐标。
        zoom: 18, // 地图的中心地理坐标。
        zoomControl: false,//不显示缩放控件
        mapZoomType: qq.maps.MapZoomType.CENTER,
        mapTypeControlOptions: {
          //设置控件的地图类型ID，ROADMAP显示普通街道地图，SATELLITE显示卫星图像，HYBRID显示卫星图像上的主要街道透明层
          mapTypeIds: [
            qq.maps.MapTypeId.ROADMAP,
            qq.maps.MapTypeId.SATELLITE,
            qq.maps.MapTypeId.HYBRID
          ],
        }
      }
      // //获取dom元素添加地图信息
      const map = new qq.maps.Map(document.getElementById("container"), myOptions);

      //创建一个marker //给定位的位置添加图片标注
      const marker = new qq.maps.Marker({
        //设置Marker的位置坐标
        position: center,
        //设置显示Marker的地图
        map: map
      });
      marker.setVisible(true);// 设置marker的可见性
      marker.setDraggable(false); //设置marker是否可以被拖拽
      const anchor = new qq.maps.Point(15, 19), //设置Marker自定义图标的属性
          origin = new qq.maps.Point(0, 0),
          size = new qq.maps.Size(32, 32), //size是图标尺寸
          icon = new qq.maps.MarkerImage(
              // "https://mapapi.qq.com/jsapi_v2/2/4/142/theme/default/imgs/marker.png",
              "/static/1.png",
              size,
              origin,
              anchor
          );
      marker.setIcon(icon);
      //设置图标结束
    },
    //上班打卡
    chock() {
      Toast.success("打卡成功！")
    },
    //外勤打卡
    unchock() {
      Toast({
        message: '管理员已关闭外勤打卡！',
        icon: require('@/assets/gps/warn.png'),
      });
    }
  }
}
</script>
<style lang="less" scoped>
.detail-font {
  font-size: 13px;
  padding-left: 2%;
  color: darkgray;
}

.lo_icon {
  height: 20px;
  padding-left: 15%;
}


.no-sign {
  padding-left: 21%;
  padding-top: 6%;
}

.my-rl-font {
  font-size: 15px;
  color: #25a4ff;
  padding-left: 1%;
}

.my-rl {
  height: 19px;
  padding-left: 2%;
}

.my-container-box {
  height: 100vh;
  width: 100vw;
  background-color: #f4f4f4;
}

#box {
  border-radius: 2%;
  margin-left: 2%;
  margin-right: 2%;
  background-color: #ffffff;
  bottom: 0;
}

#container {
  height: 300px;
  width: 100%;
}

#signIn {
  margin-top: -12%;
  margin-left: 28%;
  font-weight: bold;
  width: 3.73333rem;
  height: 3.73333rem;
  border-radius: 50%;
  box-shadow: 0px 0px 0.21333rem #25a4ff;
  font-size: 0.53333rem;
}

#fieldclock {
  margin-top: -12%;
  margin-left: 28%;
  font-weight: bold;
  width: 3.73333rem;
  height: 3.73333rem;
  border-radius: 50%;
  box-shadow: 0px 0px 15px #75778D;
  font-size: 0.53333rem;
}

.my-check {
  height: 12px;
  width: 12px;
}

.my-i {
  font-size: 13px;
  font-weight: bold;
  color: #1000e6;
}

.my-i2 {
  padding-left: 1%;
  font-size: 0.34667rem;
  //font-weight: bold;
  color: #cdd69f;
}

.my-i3 {
  padding-left: 5%;
  font-size: 13px;
  //font-weight: bold;
  color: #25a4ff;
}

#time {
  margin-left: 21%;
  font-size: 0.42667rem;
  color: #1e9fff;
  font-weight: bold;
  margin-bottom: 4%;
  margin-top: 0%;
}

.my-time {
  font-size: 16px;
  padding-top: 16%;
  color: #f4f4f4;
}

.my-icon {
  margin-left: 31%;
  margin-top: 3%;
}

.my-no-check {
  height: 14px;
}

.my-restart_locate_icon {
  margin-top: 1%;
  height: 12px;
  padding-left: 1%;
}

/deep/ .van-tag--default {
  background-color: #9acafc;
}
</style>
